package com.example.springmvc250513.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/header")
public class HeaderController {

    @RequestMapping("/getCookie")
    //获取Cookie
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            System.out.println(cookie.getName() + ":" + cookie.getValue());
        }
        return "获取cookie成功";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("bite") String bite){
        return "从Cookie中获取信息，bite:" + bite;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("userName","zhangsan");
        session.setAttribute("age",18);
        return "设置session成功";
    }

    //获取Session
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        String userName = (String)session.getAttribute("userName");
        System.out.println(session.getAttribute("age"));
        return  "从session中获取信息，userName：" + userName;
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        String userName = (String)session.getAttribute("userName");
        System.out.println(session.getAttribute("age"));
        return  "从session2中获取信息，userName：" + userName;
    }

    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("userName") String userName){
        return "从session3中获取信息，userName：" + userName;
    }

    //获取Header
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "userAgent:" + userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return "userAgent:" + userAgent;
    }

   
    @RequestMapping("/setHeader2")
    public String setHeader2(HttpServletResponse response){
        response.setHeader("My-Key","myValue");
        //设置Cookie
        Cookie cookie = new Cookie("key","value");
        response.addCookie(cookie);
        return "success";
    }
}
